// pages/settings/settings.js
const utils = require('../../utils/util.js')

Page({
  data: {
    // 基本工资设置
    payDate: '1',
    monthlySalary: '',
    yearlyBonus: '',
    includeWeekends: false,
    
    // 状态控制
    saving: false,
    resetting: false,
    loading: false
  },

  /**
   * 页面加载时初始化
   */
  onLoad: function (options) {
    this.loadSettings()
  },

  /**
   * 页面显示时重新加载设置
   */
  onShow: function () {
    this.loadSettings()
  },

  /**
   * 加载设置到表单
   */
  loadSettings: function () {
    try {
      const settings = utils.getStoredSettings()
      
      this.setData({
        payDate: settings.payDate.toString(),
        monthlySalary: settings.monthlySalary > 0 ? settings.monthlySalary.toFixed(2) : '',
        yearlyBonus: settings.yearlyBonus > 0 ? settings.yearlyBonus.toFixed(2) : '',
        includeWeekends: settings.includeWeekends
      })
      
    } catch (error) {
      console.error('加载设置失败:', error)
      utils.showToast('加载设置失败', 'error')
    }
  },

  // 表单验证
  validateForm: function (formData) {
    const payDate = parseInt(formData.payDate)
    const monthlySalary = parseFloat(formData.monthlySalary) || 0
    const yearlyBonus = parseFloat(formData.yearlyBonus) || 0
    
    if (isNaN(payDate) || payDate < 1 || payDate > 31) {
      utils.showToast('发薪日必须在1-31之间', 'error')
      return false
    }
    
    if (isNaN(monthlySalary) || monthlySalary < 0) {
      utils.showToast('月薪必须大于等于0', 'error')
      return false
    }
    
    if (isNaN(yearlyBonus) || yearlyBonus < 0) {
      utils.showToast('年终奖必须大于等于0', 'error')
      return false
    }
    
    
    return true
  },

  // 保存设置
  saveSettings: function (e) {
    const formData = e.detail.value
    
    if (!this.validateForm(formData)) {
      return
    }

    this.setData({ saving: true })

    const settings = {
      payDate: parseInt(formData.payDate),
      monthlySalary: parseFloat(formData.monthlySalary) || 0,
      yearlyBonus: parseFloat(formData.yearlyBonus) || 0,
      includeWeekends: this.data.includeWeekends,
      // 保留现有保险设置
      insurance: utils.getStoredSettings().insurance
    }

    setTimeout(() => {
      try {
        utils.saveSettings(settings)
        
        this.setData({ saving: false })
        utils.showToast('设置已保存')
        
        // 如果月薪大于0，显示成功提示
        if (settings.monthlySalary > 0) {
          setTimeout(() => {
            utils.showToast('工资计算已配置完成！', 'success')
          }, 2500)
        }
        
      } catch (error) {
        console.error('保存设置失败:', error)
        this.setData({ saving: false })
        utils.showToast('保存失败，请重试', 'error')
      }
    }, 500)
  },

  // 重置设置
  resetSettings: function () {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置所有设置为默认值吗？此操作不可撤销。',
      confirmText: '确定',
      confirmColor: '#ff3b30',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.setData({ resetting: true })
          
          setTimeout(() => {
            try {
              // 重置为默认设置
              const defaultSettings = utils.defaultSettings
              
              utils.saveSettings(defaultSettings)
              
              // 更新表单
              this.setData({
                payDate: '1',
                monthlySalary: '',
                yearlyBonus: '',
                includeWeekends: false,
                resetting: false
              })
              
              utils.showToast('设置已重置为默认值')
              
            } catch (error) {
              console.error('重置设置失败:', error)
              this.setData({ resetting: false })
              utils.showToast('重置失败，请重试', 'error')
            }
          }, 500)
        }
      }
    })
  },

  // 发薪日输入处理
  onPayDateInput: function (e) {
    let value = e.detail.value
    // 不再强制转换和限制范围，让用户可以自由输入
    this.setData({
      payDate: value
    })
  },

  // 月薪输入处理
  onMonthlySalaryInput: function (e) {
    const value = e.detail.value
    // 允许用户清空输入框
    this.setData({
      monthlySalary: value
    })
  },

  // 年终奖输入处理
  onYearlyBonusInput: function (e) {
    const value = e.detail.value
    // 允许用户清空输入框
    this.setData({
      yearlyBonus: value
    })
  },

  // 切换周末计算
  toggleWeekends: function () {
    this.setData({
      includeWeekends: !this.data.includeWeekends
    })
  },

})